import pytest
from playwright.sync_api import sync_playwright
from src.utils.get_project_root import get_project_root
from src.utils.logger import get_logger
import json
from pathlib import Path


@pytest.fixture(scope="session")
def browser():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        yield browser
        browser.close()


@pytest.fixture()
def page(browser):
    content = browser.new_context()
    page = content.new_page()
    yield page
    content.close()


@pytest.fixture()
def login_url():
    return "https://team.pescms.com/?g=Team&m=Login&a=index&back_url=Lw=="


@pytest.fixture(scope="session", autouse=True)
def configure_logger():
    get_logger("pytest")


@pytest.fixture(scope="function")
def logger(request):
    test_name = request.node.name
    return get_logger(test_name)


@pytest.fixture()
def page_with_cookie(browser):
    content = browser.new_context()
    page = content.new_page()
    cookie_file = get_project_root() / "cookies.json"
    if Path.exists(cookie_file):
        with open(cookie_file, "r", encoding="utf-8") as f:
            data = json.load(f)
            print(data)
            page.context.add_cookies(data)
    else:
        pass
    yield page
    content.close()


@pytest.fixture(scope='session', autouse=True)
def set_file_path(request):
    request.config.option.config_path = get_project_root() / "config"
    request.config.option.prompt_data = get_project_root() / "config" / "prompt_data"
    request.config.option.page_content_data = get_project_root() / "config" / "page_content_data"
    request.config.option.element_data_by_agent = get_project_root() / "config" / "page_element_by_agent"
